package util;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.noggit.JSONUtil;

public class JSONQuery extends SolrQuery {
	
	private static final long serialVersionUID = 1L;
	
	public int status;
	public int QTime;
	public long numFound;
	public long start;
	public float maxScore;
	public String JSON;
	public String docs;
	
	public JSONQuery(){
		super();
		/*
		 * defType=edismax
		 * wt=json
		 * fl=name,id,score
		 * qf=name^200%20category^10%20text
		 * start=0
		 * facet=true
		 * facet.field=cat
		 * facet.field=resourcename
		 * facet.mincount=2
		 * q=%2B*clear*%5E90
		 * fq=cat:TV&
		*/
		this.set("defType", "edismax");
		this.set("qf","name^200 category^10 text");
		this.setFields("id","name","score");
		this.setFacet(true);
		this.addFacetField("cat","resourcename");
		this.setFacetMinCount(2);
	}
	
	 /*
	{
	\"responseHeader\": {\"status\":0, \"QTime\":47, \"params\": {\"start\":\"0\",\"q\":\"+*toshi*^90\",\"fq\":\"cat:TRAITEMENT AIR\"}},
	\"response\": {\"numFound\":4, \"start\":0, \"maxScore\":0.005, \"docs\":[]},
	\"facet_counts\": {\"facet_queries\":{}, \"facet_fields\":{\"cat\":[\"TRAITEMENT AIR\",4],\"resourcename\":[\"comptoir\",4]}, \"facet_dates\":{}, \"facet_ranges\":{}}
	}
	  */
	public String toJSON(QueryResponse response){
		
		status = response.getStatus();
		QTime = response.getQTime();
		numFound = response.getResults().getNumFound();
		start = response.getResults().getStart();
		maxScore = response.getResults().getMaxScore();
		docs = JSONUtil.toJSON(response.getResults());
		
		String comma="";
		String facetFields = "";
		for(FacetField ff : response.getFacetFields()){
			facetFields += comma+"\"" + $.escape(ff.getName()) + "\":[" ;
			comma = "";
			for(Count count : ff.getValues()){
				facetFields += comma+"\""+$.escape(count.getName())+"\","+count.getCount();
				comma=",";
			}
			facetFields += "]";
		}
		
		String [] filterQueries = this.getFilterQueries();
		String fq="";
		comma = "";
		int ix = 0 ;
		while( filterQueries!= null && ix < filterQueries.length){
			fq += comma+"\""+filterQueries[ix]+"\"";
			comma = ",";
			ix++;
		}
		
		JSON = "{";
		JSON += "\"responseHeader\": {\"status\":" + status + ", \"QTime\":"+ QTime +", \"params\": {\"q\":\""+ this.getQuery() +"\",\"fq\":["+fq+"]}},";
		JSON += "\"response\": {\"numFound\":"+ numFound +", \"start\":"+ start +", \"maxScore\":"+ maxScore +", \"docs\":"+ docs +"},\n";
		JSON += "\"facet_counts\": {\"facet_fields\":{"+facetFields+"}}";
		JSON += "}";
		return JSON;
	}
}
